package me.eachann.widget.dashline;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.util.AttributeSet;
import android.util.DisplayMetrics;
import android.view.View;

import androidx.annotation.Nullable;

public class DashLine extends View {
    private Paint paintLine;
    private int dashGap = 2;
    private int dashWidth = 2;
    private int dashColor;
    private Paint mCirclePaint;
    private int style;

    public DashLine(Context context) {
        this(context, null);
    }

    public DashLine(Context context, @Nullable AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public DashLine(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        initAttrs(context, attrs, defStyleAttr);
    }

    private void initAttrs(Context context, AttributeSet attrs, int defStyleAttr) {
        TypedArray a = context.getTheme().obtainStyledAttributes(attrs, R.styleable.DashLine, defStyleAttr, 0);
        try {
            dashColor = a.getColor(R.styleable.DashLine_color, Color.BLACK);
            dashWidth = a.getDimensionPixelSize(R.styleable.DashLine_dash_line_width, dp2px(2));
            dashGap = a.getDimensionPixelSize(R.styleable.DashLine_dash_line_gap, dp2px(2));
            style = a.getInt(R.styleable.DashLine_dash_line_style, 0);
        } finally {
            a.recycle();
        }
        paintLine = new Paint();
        paintLine.setColor(dashColor);
        paintLine.setStrokeWidth(dashWidth);
        mCirclePaint = new Paint();
        mCirclePaint.setColor(Color.parseColor("#DDDDDD"));
        mCirclePaint.setAntiAlias(true);
        mCirclePaint.setStrokeWidth(dp2px(2));
        mCirclePaint.setStyle(Paint.Style.STROKE);
    }

    public void setColor(int color) {
        paintLine.setColor(color);
        invalidate();
    }

    private int dp2px(int dp) {
        DisplayMetrics dm = getContext().getResources().getDisplayMetrics();
        return (int) (dm.density * dp);
    }

    public void setHeight(int height) {
        paintLine.setStrokeWidth(dp2px(height));
        invalidate();
    }

    public void setDashGap(int dashGap) {
        this.dashGap = dp2px(dashGap);
        invalidate();
    }

    public void setDashWidth(int dashWidth) {
        this.dashWidth = dp2px(dashWidth);
        invalidate();
    }

    public void setStyle(DashLineStyle style) {
        this.style = style.getStyle();
        invalidate();
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        DashLineStyle.fromStyle(style).op(canvas,  getWidth(), getHeight(), dashWidth, dashGap, paintLine, mCirclePaint);
    }
}
